import React, { useEffect, useState, useCallback, useContext } from 'react';
import { Table, Button, message, Modal, Card, Tooltip } from 'antd';
import { formatMessage } from 'umi';
import { history } from 'umi'
import classNames from 'classnames';

import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import If from '@/components/If';
import authHelper from '@/utils/auth/helper';
import AuthComponent from '@/utils/auth/AuthComponent';

import {
    querySalaryItemList,
    onDeleteSalaryItem,
    onChangeSalaryItemStatusFirst,
    onChangeSalaryItemStatusSecond,
    queryDictMap
} from '@/services/salaryManage/salaryCalculate';
import { pageTabProps } from '@/pages/SalaryManage/utils';
import { goToSalarymainadd } from '@/pages/SalaryManage/utils/pageNavigateUtil';
import { TabMenuRouter, TabContextMenuFilter } from '@/pages/SalaryManage/components/MenuFilterRouter';
import { MENU_AUTH_CODE_MAP } from '@/pages/SalaryManage/SalaryCalculate/TemplateSetting/components/TemplateSettingRouter';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import tabMessageUtil, { useHandleRefreshMessage } from '@/pages/SalaryManage/utils/tabMessageUtil';

import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import { isSuccess } from '@/utils/request';
import OrganizationSelect from '@/components/OrganizationSelect';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';
import styles from '../index.less';
import AddStaffInfoModal from '../components/AddStatffInfoModal';
import TemplateSalaryEditModal from '../components/TemplateSalaryEditModal';

const { confirm } = Modal;
const DICT_NAME_LIST = ['salaryObjectOptions', 'salaryNotOptions', 'booleanOptions', 'taxTypeOptions'];

const StaffBaseInfo = ({ currentOrgCode }) => {
    const [baseTableList, setBaseTableList] = useState([]);
    const [tableLoading, setTableLoading] = useState(false);
    const [visible, setVisible] = useState(false);
    const [modalType, setModalType] = useState('add');
    const [editData, setEditData] = useState({});
    const getList = async () => {
        try {
            setTableLoading(true);
            const { code, data = [] } = await querySalaryItemList(currentOrgCode, 1);
            if (code === 10000) {
                setBaseTableList(data);
            }
            setTableLoading(false);
        } catch (e) {
            console.log('获取员工基础信息列表错误', e);
            setTableLoading(false);
        }
    };
    const onOpenModal = (type, data = {}) => {
        console.log(data);
        setVisible(true);
        setModalType(type);
        setEditData(data);
        if (type === 'edit') {
            setEditData(data);
        }
    };
    const onDeleteItem = async id => {
        try {
            const { code, msg } = await onDeleteSalaryItem(id);
            if (code === 10000) {
                message.success('删除成功！');
                getList();
            } else {
                message.error(msg);
            }
        } catch (e) {
            console.log(e);
        }
    };
    const onChangeStatus = async (id, used) => {
        try {
            const { code, msg } = await onChangeSalaryItemStatusFirst(id, used ? 0 : 1);
            if (code === 10000) {
                message.success(`${used ? '禁用成功' : '启用成功'}！`);
                getList();
            } else {
                message.error(msg);
            }
        } catch (e) {
            console.log(e);
        }
    };
    const onCloseModal = useCallback(() => {
        setVisible(false);
    }, []);
    const onRefreshList = useCallback(() => {
        setVisible(false);
        getList();
    }, []);
    const columns = [
        {
            title: '基础信息',
            dataIndex: 'itemName',
            key: 'itemName',
            width: 120
        },
        {
            title: '来源类型',
            dataIndex: 'sourceTypeName',
            key: 'sourceTypeName',
            width: 150
        },
        {
            title: '取值描述',
            dataIndex: 'showName',
            key: 'showName',
            width: '30%'
        },
        {
            title: '备注说明',
            dataIndex: 'remark',
            key: 'remark',
            render(text) {
                return (
                    <span
                        style={{
                            display: 'inline-block',
                            whiteSpace: 'break-spaces',
                            wordBreak: 'break-all'
                        }}
                    >
                        {text}
                    </span>
                );
            }
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            render: (text, record) => (
                <div>
                    <AutoDivider>
                        <If
                            condition={authHelper.checkCode('finance:salary:computation:setting:itemlist:employeeedit')}
                        >
                            <Tooltip title="编辑">
                                <Button
                                    className={salaryStyle.operateIcon}
                                    disabled={record.fixed}
                                    onClick={() => {
                                        onOpenModal('edit', record);
                                    }}
                                >
                                    <i className={classNames('iconfont', 'iconlistfunction_edit_icon_default')} />
                                </Button>
                            </Tooltip>
                        </If>
                        <If condition={authHelper.checkCode('finance:salary:computation:setting:itemlist:employeedel')}>
                            <Tooltip title="删除">
                                <Button
                                    className={salaryStyle.operateIcon}
                                    disabled={record.fixed || record.used}
                                    onClick={() => {
                                        confirm({
                                            title: '确定删除',
                                            content: `员工基础信息中的【${record.itemName}】吗？`,
                                            okText: '确定',
                                            cancelText: '取消',
                                            onOk() {
                                                onDeleteItem(record.id);
                                            }
                                        });
                                    }}
                                >
                                    <i className={classNames('iconfont', 'iconDeleteIcon')} />
                                </Button>
                            </Tooltip>
                        </If>
                        <If
                            condition={authHelper.checkCode(
                                'finance:salary:computation:setting:itemlist:employeedisable'
                            )}
                        >
                            <Tooltip title={record.status === 1 || record.fixed ? '停止使用' : '重新启用'}>
                                <Button
                                    className={salaryStyle.operateIcon}
                                    onClick={() => {
                                        const isUsed = record.status === 1;
                                        const title = isUsed ? '确定暂停使用' : '确定重新启用';
                                        const hintText = isUsed
                                            ? '暂停使用后只对后面操作产生影响，对已经引用的不产生影响'
                                            : '重新使用后只对后面操作产生影响，对历史已发薪的不产生影响';
                                        confirm({
                                            title,
                                            content: (
                                                <div>
                                                    <div>员工基础信息中的【{record.itemName}】吗？</div>
                                                    <span>{hintText}</span>
                                                </div>
                                            ),
                                            okText: '确定',
                                            cancelText: '取消',
                                            onOk() {
                                                onChangeStatus(record.id, isUsed);
                                            }
                                        });
                                    }}
                                    disabled={record.fixed}
                                >
                                    <i
                                        className={classNames(
                                            'iconfont',
                                            record.status === 1 || record.fixed
                                                ? 'iconlistfunction_auditcanceled_icon_default'
                                                : 'iconlistfunction_reject_icon_default'
                                        )}
                                    />
                                </Button>
                            </Tooltip>
                        </If>
                    </AutoDivider>
                </div>
            )
        }
    ];
    useEffect(() => {
        getList();
    }, []);
    return (
        <div className={styles.salaryContent}>
            <div className={styles.titleWrap}>
                <div className={styles.leftTitleWrap}>
                    <div className={styles.title}>
                        {formatMessage({ id: 'templateSetting.partTemplate.staffBaseInfo' })}
                    </div>
                </div>
                <div>
                    <AuthComponent code="finance:salary:computation:setting:itemlist:addemployee">
                        <a
                            onClick={e => {
                                e.preventDefault();
                                onOpenModal('add');
                            }}
                        >
                            {formatMessage({ id: 'templateSetting.partTemplate.addStaffBase' })}
                        </a>
                    </AuthComponent>
                </div>
            </div>
            <Table rowKey="id" columns={columns} dataSource={baseTableList} loading={tableLoading} pagination={false} />
            <If condition={visible}>
                <AddStaffInfoModal
                    visible={visible}
                    type={modalType}
                    editData={editData}
                    onCancel={onCloseModal}
                    onChange={onRefreshList}
                    currentOrgCode={currentOrgCode}
                />
            </If>
        </div>
    );
};
const SalaryExtraItem = ({ itemType = 'add', dictList = {}, organizationCode }) => {
    const [tableData, setTableData] = useState([]);
    const [editData, setEditData] = useState({});
    const [tableLoading, setTableLoading] = useState(false);
    const [addMainVisible, setAddMainVisible] = useState(false);
    const labelList = {
        add: {
            title: 'templateSetting.salaryTemplate.salaryAddItem',
            extraAddBtn: 'templateSetting.partTemplate.addSalaryAddItem',
            mainAddBtn: 'templateSetting.partTemplate.addSalaryMain'
        },
        reduce: {
            title: 'templateSetting.salaryTemplate.salaryReduceItem',
            extraAddBtn: 'templateSetting.partTemplate.addSalaryReduceItem',
            mainAddBtn: 'templateSetting.partTemplate.addSalaryMain'
        }
    };
    const handleData = (key, data) => {
        // 获取到合并数据的重复数量
        const sunArr = data.reduce((acc, cur) => {
            if (!acc[cur[key]]) {
                acc[cur[key]] = 0;
            }
            // eslint-disable-next-line no-plusplus
            acc[cur[key]]++;
            return acc;
        }, {});
        console.log('分类结果', sunArr);
        let obj = {};
        const validArr = {};
        // 给渲染数据增加合并行数
        const newArr = data.map(item => {
            obj = { ...item };
            if (sunArr[item[key]] && !validArr[item[key]]) {
                obj.rowLength = sunArr[item[key]];
                validArr[item[key]] = true;
            }
            return obj;
        });
        console.log('处理完的数据', newArr);
        setTableData(newArr);
    };
    const getTableData = async () => {
        try {
            setTableLoading(true);
            const { code, data = [] } = await querySalaryItemList(organizationCode, itemType === 'add' ? 2 : 3);
            console.log('薪资项列表=======>', data);
            if (code === 10000) {
                handleData('parentName', data);
            }
            setTableLoading(false);
        } catch (e) {
            console.log('获取薪资项列表错误', e);
            setTableLoading(false);
        }
    };
    const onOpenAddMainModal = (type, data = {}) => {
        console.log('编辑数据', data);
        setAddMainVisible(true);
        setEditData(data);
    };
    const onDeleteItem = async id => {
        try {
            const { code, msg } = await onDeleteSalaryItem(id);
            if (code === 10000) {
                tabMessageUtil.noticeRefreshByPathname('/finance/salary/salarytemplateedit');
                message.success('删除成功！');
                getTableData();
            } else {
                message.error(msg);
            }
        } catch (e) {
            console.log(e);
        }
    };
    const onChangeStatus = async (id, used) => {
        try {
            const postStatus = used ? 0 : 1;
            const handleResponse = (response, confirmFn = () => {}) => {
                const { code: responseCode, msg: responseMsg, data: responseData = {} } = response;
                if (!isSuccess(responseCode)) {
                    message.error(responseMsg);
                    return;
                }
                if (responseData.enableLevel === 1) {
                    message.success(`${used ? '禁用成功' : '启用成功'}！`);
                    tabMessageUtil.noticeRefreshByPathname('/finance/salary/salarytemplateedit');
                    getTableData();
                } else if (responseData.enableLevel === 3) {
                    message.success(`${used ? '禁用' : '启用'}失败，薪资条已被下发并在审核中！`);
                } else {
                    confirmFn();
                }
            };

            const firstResponse = await onChangeSalaryItemStatusFirst(id, postStatus);
            handleResponse(firstResponse, () => {
                confirm({
                    title: used ? '确定暂停使用' : '确定重新启用',
                    content: `${firstResponse.data.month}月薪资已生成，是否继续`,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: async () => {
                        const secondResponse = await onChangeSalaryItemStatusSecond(id, postStatus);
                        handleResponse(secondResponse);
                    }
                });
            });
        } catch (e) {
            console.log(e);
        }
    };
    const getObjectValue = (key, value) => {
        let v = value;
        if (dictList[key]) {
            v = dictList[key][value];
        }
        return {
            children: v
        };
    };
    const onCloseModal = useCallback(() => {
        setAddMainVisible(false);
    }, []);
    const onRefreshList = useCallback(() => {
        onCloseModal();
        getTableData();
    }, []);
    const columns = [
        {
            dataIndex: 'parentName',
            title: '上级薪资项',
            key: 'parentName',
            width: 120,
            className: styles.salaryTableColumns,
            render: (text, record) => {
                // { /* <div style={{ minHeight: '40px' }}> */ }
                // { /*    <div className={styles.salaryTableColumnsItem}> */ }
                // { /*        <span>{text}</span> */ }
                // { /*        <div className={styles.salaryItemModalWrap}> */ }
                // { /*            <Button */ }
                // { /*                type="link" */ }
                // { /*                style={{ color: 'rgba(255,255,255,0.85)' }} */ }
                // { /*                onClick={() => { */ }
                // { /*                    onOpenAddItemModal('edit', record); */ }
                // { /*                }} */ }
                // { /*            > */ }
                // { /*                编辑 */ }
                // { /*            </Button> */ }
                // { /*            <Button */ }
                // { /*                type="link" */ }
                // { /*                style={{ color: record.id ? 'rgba(255,255,255,0.3)' : 'rgba(255,255,255,0.85)' }} */ }
                // { /*                onClick={() => { */ }
                // { /*                    confirm({ */ }
                // { /*                        title: '确定删除', */ }
                // { /*                        content: `${itemType === 'add' ? '薪资加项' : '薪资减项'}中的【${record.parentName}】吗`, */ }
                // { /*                        okText: '确定', */ }
                // { /*                        cancelText: '取消', */ }
                // { /*                        onOk() { */ }
                // { /*                            onDeleteItem(record.parentId); */ }
                // { /*                        } */ }
                // { /*                    }); */ }
                // { /*                }} */ }
                // { /*                disabled={record.id} */ }
                // { /*            > */ }
                // { /*                删除 */ }
                // { /*            </Button> */ }
                // { /*        </div> */ }
                // { /*    </div> */ }
                // { /* </div>, */ }
                const obj = {
                    children: text,
                    props: { rowSpan: 0 }
                };
                if (record.rowLength) {
                    obj.props.rowSpan = record.rowLength;
                }
                return obj;
            }
        },
        {
            title: '薪资要素',
            dataIndex: 'itemName',
            key: 'itemName',
            width: 120
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 80,
            align: 'center',
            render(status) {
                return +status === 1 ? '启用' : '禁用';
            }
        },
        {
            title: '计薪对象',
            dataIndex: 'salaryObject',
            key: 'salaryObject',
            width: 220,
            render: text => getObjectValue('salaryObjectOptions', text)
        },
        {
            title: '不计薪条件',
            dataIndex: 'salaryNot',
            key: 'salaryNot',
            width: 120,
            render: text => getObjectValue('salaryNotOptions', text)
        },
        {
            title: 'Offer字段',
            dataIndex: 'isOffer',
            key: 'isOffer',
            width: 120,
            render: (text, record) => (record.id && text ? '是' : '否')
        },
        {
            title: '加减项',
            dataIndex: 'taxType',
            key: 'taxType',
            width: 120,
            render: text => getObjectValue('taxTypeOptions', text)
        },
        {
            title: '来源类型',
            dataIndex: 'sourceTypeName',
            key: 'sourceTypeName',
            width: 120
        },
        {
            title: '取值描述',
            dataIndex: 'showName',
            key: 'showName',
            width: 200
        },
        {
            title: '备注说明',
            dataIndex: 'remark',
            key: 'remark',
            render(text) {
                return (
                    <span
                        style={{
                            display: 'inline-block',
                            whiteSpace: 'break-spaces',
                            wordBreak: 'break-all'
                        }}
                    >
                        {text}
                    </span>
                );
            }
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 180,
            render: (text, record) =>
                record.id && (
                    <div>
                        <AutoDivider>
                            <If
                                condition={authHelper.checkCode(
                                    'finance:salary:computation:setting:itemlist:salaryitemedit'
                                )}
                            >
                                <Tooltip title="编辑">
                                    <Button
                                        className={salaryStyle.operateIcon}
                                        disabled={record.fixed}
                                        onClick={() => {
                                            onOpenAddMainModal('edit', record);
                                        }}
                                    >
                                        <i className={classNames('iconfont', 'iconlistfunction_edit_icon_default')} />
                                    </Button>
                                </Tooltip>
                            </If>
                            <If
                                condition={authHelper.checkCode(
                                    'finance:salary:computation:setting:itemlist:salaryitemedel'
                                )}
                            >
                                <Tooltip title="删除">
                                    <Button
                                        className={salaryStyle.operateIcon}
                                        disabled={record.fixed || record.used}
                                        onClick={() => {
                                            confirm({
                                                title: '确定删除',
                                                content: `${record.parentName}中的【${record.itemName}】吗`,
                                                okText: '确定',
                                                cancelText: '取消',
                                                onOk() {
                                                    onDeleteItem(record.id);
                                                }
                                            });
                                        }}
                                    >
                                        <i className={classNames('iconfont', 'iconDeleteIcon')} />
                                    </Button>
                                </Tooltip>
                            </If>
                            <If
                                condition={authHelper.checkCode(
                                    'finance:salary:computation:setting:itemlist:salaryitemedisable'
                                )}
                            >
                                <Tooltip title={record.status === 1 ? '停止使用' : '重新启用'}>
                                    <Button
                                        className={salaryStyle.operateIcon}
                                        onClick={() => {
                                            const isUsed = record.status === 1;
                                            const title = isUsed ? '确定暂停使用' : '确定重新启用';
                                            const hintText = isUsed
                                                ? '暂停使用后只对后面操作产生影响，对已经引用的不产生影响'
                                                : '重新使用后只对后面操作产生影响，对历史已发薪的不产生影响';
                                            confirm({
                                                title,
                                                content: (
                                                    <div>
                                                        <div>
                                                            {record.parentName}中的【{record.itemName}】吗
                                                        </div>
                                                        <span>{hintText}</span>
                                                    </div>
                                                ),
                                                okText: '确定',
                                                cancelText: '取消',
                                                onOk() {
                                                    onChangeStatus(record.id, isUsed);
                                                }
                                            });
                                        }}
                                    >
                                        <i
                                            className={classNames(
                                                'iconfont',
                                                record.status === 1
                                                    ? 'iconlistfunction_auditcanceled_icon_default'
                                                    : 'iconlistfunction_reject_icon_default'
                                            )}
                                        />
                                    </Button>
                                </Tooltip>
                            </If>
                            <Tooltip title="详情">
                                <Button
                                    className={salaryStyle.operateIcon}
                                    onClick={() =>
                                        goToSalarymainadd(
                                            {
                                                query: {
                                                    itemType: record.itemType === 2 ? 'add' : 'reduce',
                                                    id: record.id,
                                                    disabled: true,
                                                    organizationCode
                                                }
                                            },
                                            'detail'
                                        )
                                    }
                                >
                                    <i
                                        className={classNames(
                                            'iconfont',
                                            'iconlistfunction_viewinterview_icon_default'
                                        )}
                                    />
                                </Button>
                            </Tooltip>
                        </AutoDivider>
                    </div>
                )
        }
    ];
    useEffect(() => {
        getTableData();
    }, []);
    return (
        <div className={styles.salaryContent}>
            <div className={styles.titleWrap}>
                <div className={styles.leftTitleWrap}>
                    <div className={styles.title}>{formatMessage({ id: labelList[itemType].title })}</div>
                </div>
                <div>
                    {/*
                        <a
                        onClick={e => {
                            e.preventDefault();
                            onOpenAddItemModal('add');
                        }}
                    >
                        {formatMessage({ id: labelList[itemType].extraAddBtn })}
                    </a>
                    <Divider type="vertical" />
                    */}
                    <AuthComponent code="finance:salary:computation:setting:itemlist:addsalaryitem">
                        <a
                            onClick={e => {
                                e.preventDefault();
                                tabMessageUtil.openMemoTabByRouterConfig({
                                    pathname: '/finance/salary/salarymainadd',
                                    query: {
                                        itemType,
                                        organizationCode
                                    },
                                    state: {
                                        tabRoute: true,
                                        tabRefresh: true
                                    }
                                });
                            }}
                        >
                            {formatMessage({ id: labelList[itemType].extraAddBtn })}
                        </a>
                    </AuthComponent>
                </div>
            </div>
            <Table
                rowKey="id"
                className={styles.salaryTable}
                bordered
                columns={columns}
                dataSource={tableData}
                loading={tableLoading}
                pagination={false}
                scroll={{ x: 'calc(1000px + 50%)' }}
                rowClassName={() => styles.salaryTable}
            />
            <TemplateSalaryEditModal
                itemType={itemType}
                visible={addMainVisible}
                editData={editData}
                onCancel={onCloseModal}
                onChange={onRefreshList}
                currentOrgCode={organizationCode}
            />
        </div>
    );
};
const PartTemplate = () => {
    const [dictList, setDictList] = useState({});
    const {
        store: { selectOrganizationCode, defaultOrganization },
        mergeTabStore
    } = useContext(TabStoreContext);
    // 初始化头部没有默认使用其他公用code, 再没有使用默认
    const [organizationCode, setOrganizationCode] = useState(selectOrganizationCode);

    useEffect(() => {
        // 不存在code,默认用左边机构选择code
        if (organizationCode) return;
        setOrganizationCode(defaultOrganization?.organizationCode);
        mergeTabStore({ selectOrganizationCode: defaultOrganization?.organizationCode });
    }, [defaultOrganization]);

    const getDictList = async () => {
        try {
            const confTypes = DICT_NAME_LIST.join(',');
            const { code, data } = await queryDictMap(confTypes);
            if (code === 10000) {
                console.log('表格数据字典列表', data);
                setDictList(data);
            }
        } catch (e) {
            console.log(e);
        }
    };
    useEffect(() => {
        getDictList();
    }, []);

    const goToLogPage = () => {
        history.push({
            pathname: '/finance/salary/calculate/templatesetting/parttemplatelog',
            query: {
                organizationCode
            },
            state: { tabRoute: true, tabRefresh: true }
        });
    };
    const handleOrganizationChange = useCallback(
        value => {
            if (selectOrganizationCode !== value) {
                setOrganizationCode(value);
                mergeTabStore({
                    selectOrganizationCode: value,
                    countryNameCode: null
                });
            }
        },
        [mergeTabStore, selectOrganizationCode]
    );
    useHandleRefreshMessage();
    return (
        <PageHeaderWrapper type="success">
            <TabContextMenuFilter enableDefaultSelect={false}>
                <TabMenuRouter
                    authCodeMap={MENU_AUTH_CODE_MAP}
                    type="templateSetting"
                    extraButton={
                        <div style={{ display: 'flex' }}>
                            <div className={salaryStyle.mr12} style={{ display: 'flex' }}>
                                <OrganizationSelect
                                    isStrictly
                                    isNeedPermission
                                    style={{ width: 220 }}
                                    onChange={handleOrganizationChange}
                                    value={organizationCode}
                                    allowClear={false}
                                    dropdownMatchSelectWidth
                                />
                            </div>
                            <div>
                                <Button onClick={() => goToLogPage(organizationCode)}>操作日志</Button>
                            </div>
                        </div>
                    }
                >
                    <Card
                        title=""
                        bordered={false}
                        // extra={
                        //     <div
                        //         style={{
                        //             display: 'flex',
                        //             lineHeight: '31px'
                        //         }}
                        //     >
                        //         <OrganizationNameHead organizationCode={organizationCode} />
                        //         <Button onClick={() => goToLogPage(organizationCode)} className={salaryStyle.ml12}>
                        //             操作日志
                        //         </Button>
                        //     </div>
                        // }
                        {...pageTabProps()}
                    >
                        <div className={styles.container}>
                            <StaffBaseInfo currentOrgCode={organizationCode} />
                            <SalaryExtraItem itemType="add" dictList={dictList} organizationCode={organizationCode} />
                            <SalaryExtraItem
                                itemType="reduce"
                                dictList={dictList}
                                organizationCode={organizationCode}
                            />
                        </div>
                    </Card>
                </TabMenuRouter>
            </TabContextMenuFilter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(PartTemplate);
